今天提到的是 CoreLocation
這個是定位的一環
你要做出定位就必須使用到他
class LocationFetcher: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var lastKnownLocation: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
//這裡就是請求
func start() {
manager.requestAlwaysAuthorization()
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
lastKnownLocation = (locations.first?.coordinate)!
}
}
那首先你要讓手機同意你使用定位功能
而且你必須在xcode那邊去先做請求地確認 info.plist 之後再請使用者確認
privacy-location when in use usag...
privacy-location usage description
privacy-location always and when I
start()
的部分就是去請求使用者確認
在主視圖的時候
先init去做部屬
讓他先初始化
lastKnownLocation 激活讓他讀取你的位置
裡用主介面的按鈕激活
Button(action: {
print("回到座標點")
self.locationFetcher.start()
let location = self.locationFetcher.lastKnownLocation
self.mapViewState.center = location
}
) {
Image(systemName: "location")
}
mapViewState.center
會使使用者位置回到 lastKnownLocation